package site.syksy.qingzhou.upms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.syksy.qingzhou.upms.constant.RouteLinkType;
import site.syksy.qingzhou.upms.domain.RouteDO;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author Raspberry
 */
@Service
public class CommonService {

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleMenuService roleMenuService;

    @Autowired
    RouteLinkService routeLinkService;

    @Autowired
    RouteService routeService;

    /**
     * 第一步、根据用户id,查出用户的角色；
     * 第二步、通过角色，查出关联的菜单；
     * 第三步、根据角色和菜单，分别查询出关联的路由ID，将路由ID合并去重；
     * 第四步、 根据路由ID集合，查询从路由信息。
     *
     * @param userId
     * @param requestMethod
     * @return
     */
    public List<RouteDO> selectRouteByUserId(String userId, String requestMethod) {
        List<String> routeIdList = new ArrayList<>();
        List<String> roleIds = userRoleService.selectRoleIdsByUserId(userId);
        List<String> menuIds = roleMenuService.selectMenuIdsByRoleIds(roleIds);
        if (roleIds != null && roleIds.size() > 0) {
            List<String> roleRouteIdList = routeLinkService.selectRouteIdByTarget(roleIds, RouteLinkType.ROLE);
            routeIdList.addAll(roleRouteIdList);
        }
        if (menuIds != null && menuIds.size() > 0) {
            List<String> menuRouteIdList = routeLinkService.selectRouteIdByTarget(menuIds, RouteLinkType.MENU);
            routeIdList.addAll(menuRouteIdList);
        }
        HashSet hashSet = new HashSet(routeIdList);
        routeIdList.clear();
        routeIdList.addAll(hashSet);
        if(routeIdList.size()>0){
            List<RouteDO> routeDOList = routeService.selectByIdsAndRequestMethod(routeIdList,requestMethod);
            return routeDOList;
        }else{
            return null;
        }

    }

}
